import React, { useState, useCallback, useEffect } from 'react'
import { genImageFromBase64 } from '../components/common/genImageFromBase64'
import { mergeStyle } from '../components/common/mergeStyle'
import basicStyle from '../components/common/basic.scss'
import classnames from 'classnames'
import { getStepFullLog } from '../source/getData'
import { notify } from '../source/notify'
import { NotifyType } from '../common/enums'

export const AssertImageEqualViewer = ({ planId, stepId }) => {
    const [result, setResult] = useState(null)

    const [expanded, setExpanded] = useState(false)

    useEffect(() => {
        if (!result && expanded) {
            getStepFullLog({ planId, stepId })
                .then(fullLog => {
                    if (fullLog && fullLog.result) {
                        setResult(fullLog.result)
                    } else {
                        notify(NotifyType.error, '日志详情为空')
                        console.error(fullLog)
                    }
                })
        }
    }, [result, expanded, planId, stepId])

    const toggleExpanded = useCallback(() => setExpanded(current => !current), [])

    return <React.Fragment>
        <span onClick={toggleExpanded} title={expanded ? '收起截图' : '展开截图'}
            className={mergeStyle(basicStyle, classnames('icon', { expanded: !expanded, collapsed: expanded }))} />
        {
            expanded && result && <div className={basicStyle.no_select}>
                <p>基准环境：</p>
                {genImageFromBase64(result.expected, true)}
                <p>测试环境：</p>
                {genImageFromBase64(result.actual, true)}
                {(!result.valid || true) && <React.Fragment>
                    <p>截图差异：</p>
                    {genImageFromBase64(result.difference, true)}
                </React.Fragment>}
            </div>
        }
    </React.Fragment>
}